<?php

namespace App\Jobs;

use App\News;
use App\NewsImage;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Exception;
use Illuminate\Support\Facades\Cache;

class NewsInsert implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected $data;
    protected $url;
    protected $table;

    public $tries = 1;// 尝试添加次数

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($data, $table)
    {
        $this->data  = $data;
        $this->table = $table;
    }


    /**
     * Execute the job.
     * @return void
     */

    public function handle()
    {
        $url   = 'https://news.zhibo8.cc';
        $value = $this->data;
        $table = $this->table;
        try {
            $name = $value['filename'];
            $res  = (new News())->setTable($table)->where('index', '=', $name)->first();

            if (isset($value['label'])) {
                $insert['label'] = $value['label'];
            } else {
                $insert['label'] = $value['lable'];
            }

            if (is_null($res) === false || strpos($insert['label'], '足球') === false) { // 剔除没有足球标签,
                echo '已经添加';
            } else {
                // 准备数据
                $insert['title']       = $value['title'];
                $insert['from']        = $value['from_name'];
                $insert['update_time'] = strtotime($value['createtime']);
                $insert['index']       = $value['filename'];

                $str = file_get_contents($url . '/zuqiu/' . date('Y-m-d', $insert['update_time']) . '/' . $value['filename'] . '.htm');  // 采集主体新闻内容
// 描述
                preg_match_all('/<meta\s+name=[\"\']Description[\"\']\s+content=[\"\']([\S\s]*?)[\"\']\/?>/im', $str, $matchesD);
                if (!empty($matchesD[1])) {
                    $des = $matchesD[1][0];
                    str_replace('直播吧', '', $des);
                    $insert['description'] = $des;
                }
                // 文章详细内容
                preg_match_all('/<p.*?>(.*?)(?=<\/p>)/im', $str, $matches);
                $string = '';
                if (!empty($matches[0])) {
                    foreach ($matches[0] as $v) {
                        $string .= $v;
                    }
                }
                $id     = (new News())->setTable($table)->insertGetId($insert);
                $images = [];
                // 保存图片
                $ext = 'gif|jpg|jpeg|bmp|png';
                preg_match_all("/(src)=([\"|']?)([^ \"'>]+\.($ext))\\2/i", $string, $matches2);
                if (!empty($matches2[0])) {
                    foreach ($matches2[0] as $k => $v) {
                        $num      = $k + 1;
                        $v        = str_replace('src=', '', $v);
                        $v        = str_replace('"', '', $v);
                        $images[] = [
                            'imgsrc'  => $v,
                            'news_id' => $id,
                            'status'  => 0,
                            'sort'    => $num
                        ];
                        // $all    = static::download($v, './public/images/' . date('Y-m-d', strtotime($value['createtime'])));
                        $string = str_replace($v, '{{imgsrc' . $num . '}}', $string);
                    }
                }
                $insert['content'] = $string;
                (new News())->setTable($table)->where('id', '=', $id)->update(['content' => $string]);
                if (!empty($images)) {
                    NewsImage::insert($images);
                }
                echo '完成:' . $id;
            }
        } catch (Exception $exception) {
            echo '系统异常';
        }
        // 释放资源
        //unset($this->table);
        unset($this->value);
        unset($value);
        //unset($table);

//            var_dump($insert['content']);
//            die;
    }


    /**
     * 下载远程图片保存到本地
     * @access public
     * @return array
     * @params string $url 远程图片地址
     * @params string $save_dir 需要保存的地址
     * @params string $filename 保存文件名
     * @since 1.0
     * @author
     */
    protected static function download($url, $save_dir = './public/upload/loan/', $filename = '')
    {
        if (trim($save_dir) == '')
            $save_dir = './';
        if (trim($filename) == '') {//保存文件名
            $allowExt = array('.gif', '.jpg', '.jpeg', '.png', '.bmp');
            $ext      = strrchr($url, '.');
            if (!in_array($ext, $allowExt)) {
                return array('file_name' => '', 'save_path' => '', 'error' => 3);
            }
        }
        if (0 !== strrpos($save_dir, '/'))
            $save_dir .= '/';

        //创建保存目录
        if (!file_exists($save_dir) && !mkdir($save_dir, 0777, true))
            return array('file_name' => '', 'save_path' => '', 'error' => 5);

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 信任任何证书
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
        $file = curl_exec($ch);
        curl_close($ch);
        $filename = pathinfo($url, PATHINFO_BASENAME);
        $resource = fopen($save_dir . $filename, 'a');
        fwrite($resource, $file);
        fclose($resource);
        unset($file, $url);
        return array('file_name' => $filename, 'save_path' => $save_dir . $filename, 'error' => 0);
    }


    /**
     * 任务失败的处理过程
     *
     * @param Exception $exception
     * @return void
     */
    public
    function failed(Exception $exception)
    {
        // 给用户发送任务失败的通知，等等……
        echo '任务失败';
        return;
    }
}
